//
//  ConfirmProductListCell.swift
//  koolcar
//
//  Created by xiantian on 2023/11/2.
//

import UIKit

class ConfirmProductListCell: UITableViewCell {
    var data: PreviewProductOrderDataModel?
    var bkgView: UIView!
    var tableView: UITableView!
    var dataArray: [PreviewProductItemModel] = []
    
    var orderModel: OrderInfoModel!
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = Theme.viewBkgGrayColor
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth - 28, height: 88), style: .grouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        tableView.register(ConfirmProductCell.self, forCellReuseIdentifier: "ConfirmProductCell")
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        tableView.layer.masksToBounds = true
        tableView.layer.cornerRadius = 8
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 2
        tableView.isScrollEnabled = false
        contentView.addSubview(tableView)
        self.addSnpLayout()
    }
    
    private func createHeaderView() -> UIView {
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth - 28, height: 44))
        header.backgroundColor = .white
        
        let iconImgView = UIImageView()
//         iconImgView.image = UIImage.init(named: "icon_order_store")
        iconImgView.image = UIImage.init(named: "order_list")
        iconImgView.contentMode = .scaleAspectFit
        iconImgView.clipsToBounds = true
        header.addSubview(iconImgView)
        
        let titleLab = UILabel()
        titleLab.textColor = Theme.titleLabColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .left
        titleLab.text = MMLocalizedString("confirm_list", comment: "货品清单")
        header.addSubview(titleLab)

        if self.orderModel != nil{//商城
            titleLab.text = MMLocalizedString("store", comment: "商城")
        }
        
        
        iconImgView.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.centerY.equalToSuperview()
            make.width.equalTo(14)
            make.height.equalTo(14)
        }
        
        titleLab.snp.makeConstraints { make in
            make.left.equalTo(iconImgView.snp.right).offset(10)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
            make.right.equalTo(-14)
        }
        
        return header
    }
    
    
    private func createFooterView() -> UIView {
        let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth - 28, height: 40))
        footer.clipsToBounds = true
        footer.backgroundColor = .white
        
        let titleLab = UILabel()
        titleLab.textColor = Theme.titleLabColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .left
        titleLab.text = MMLocalizedString("confirm_total", comment: "总计")
        footer.addSubview(titleLab)
        
        let totalPriceLab = UILabel()
        totalPriceLab.textColor = Theme.titleLabColor
        totalPriceLab.backgroundColor = UIColor.clear
        totalPriceLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        totalPriceLab.numberOfLines = 1
        totalPriceLab.lineBreakMode = .byTruncatingTail
        totalPriceLab.textAlignment = .right
        footer.addSubview(totalPriceLab)
        
        
        if self.orderModel != nil{
            //商城
            let price = XTManageCenter.showPriceInComma(source: (self.orderModel?.price ?? 0).cleanZero)
            totalPriceLab.text = String(format: "%@%@", XTManageCenter.currentSign(), price)
                    footer.addSubview(totalPriceLab)
        }else{
            let price = XTManageCenter.showPriceInComma(source: (self.data?.price ?? 0).cleanZero)
            totalPriceLab.text = String(format: "%@%@", XTManageCenter.currentSign(), price)
        }
        
        titleLab.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
        
        totalPriceLab.snp.makeConstraints { make in
            make.right.equalTo(-14)
            make.top.bottom.equalTo(0)
            make.left.equalTo(titleLab.snp.right)
        }
        return footer
    }
    
    private func addSnpLayout(){
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.width.equalTo(kScreenWidth - 28)
            make.top.equalTo(10)
            make.height.greaterThanOrEqualTo(88)
            make.bottom.equalTo(0).priority(.high)
        }
        self.layoutIfNeeded()
    }
    
    func setConfirmProductListCell(data: PreviewProductOrderDataModel? = nil){
        self.data = data
        self.dataArray = data?.items ?? []
        self.tableView.frame.size.height = 9999
        self.tableView.reloadData()
        self.tableView.layoutSubviews()
        self.tableView.layoutIfNeeded()
        let tempH = self.tableView.contentSize.height
        self.tableView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(tempH)
        }
        self.updateConstraints()
        self.layoutIfNeeded()
    }
    
    
    //订单详情（商品）
    func setModel(model: OrderInfoModel){
        self.orderModel = model
        self.dataArray = model.orderitemDTOList ?? []
        self.tableView.frame.size.height = 9999
        self.tableView.reloadData()
        self.tableView.layoutSubviews()
        self.tableView.layoutIfNeeded()
        let tempH = self.tableView.contentSize.height
        self.tableView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(tempH)
        }
        self.updateConstraints()
        self.layoutIfNeeded()
    }
    
    
    
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension ConfirmProductListCell: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return self.createHeaderView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return self.createFooterView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ConfirmProductCell", for: indexPath) as! ConfirmProductCell
        if self.dataArray.count > indexPath.row {
            let item = self.dataArray[indexPath.row]
            cell.setConfirmProductCell(data: item)
        }
        cell.updateConstraints()
        cell.layoutIfNeeded()
        cell.clipsToBounds = true
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        printLog("33")
        if self.orderModel != nil{//商城
            if self.dataArray.count > indexPath.row{
//                let model = self.dataArray[indexPath.row]
//                let vc = ProductDetailsViewController()
//                vc.id = model.id ?? 0
//                self.viewController().navigationController?.pushViewController(vc, animated: true)
            }
     
        }
    }
}
